package cn.itcast.web.action;

import cn.itcast.domain.delivery.Promotion;
import cn.itcast.service.PromotionService;
import cn.itcast.utils.ResponseUtils;
import cn.itcast.web.action.common.BaseAction;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Namespace("/")
@ParentPackage("struts-default")
@Controller
@Scope("prototype")
@Actions
public class PromotionBosAction extends BaseAction<Promotion> {
    // name="titleImgFile"
    private File titleImgFile;
    private String titleImgFileFileName;
    private String titleImgFileContentType;

    @Autowired
    private PromotionService promotionService;

    public void setTitleImgFile(File titleImgFile) {
        this.titleImgFile = titleImgFile;
    }

    public void setTitleImgFileFileName(String titleImgFileFileName) {
        this.titleImgFileFileName = titleImgFileFileName;
    }

    public void setTitleImgFileContentType(String titleImgFileContentType) {
        this.titleImgFileContentType = titleImgFileContentType;
    }

    //action="../../promotion_save.action" 保存宣传信息
    @Action(value = "promotion_save", results = {@Result(name = "success", location = "./pages/delivery/promotion_add.html", type = "redirect")})
    public String save() {
        //先上传文件 再保存model
        String realPath = "F://upload/";
        String savePath = "/upload/";
        UUID uuid = UUID.randomUUID();
        String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
        titleImgFileFileName = uuid + ext;
        try {
            FileUtils.copyFile(titleImgFile, new File(realPath, titleImgFileFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        model.setTitleImg(savePath + "/" + titleImgFileFileName);
        promotionService.save(model);
        return SUCCESS;
    }
//    url:"../../promotion_pageQuery.action", 无条件分页
    //page 当前页 rows 每页记录数
    @Action(value = "promotion_pageQuery")
    public String pageQuery() {
        Pageable pageable = new PageRequest(page - 1, rows);
        Page<Promotion>pageData= promotionService.findPageData(pageable);
        Map<String,Object> results=new HashMap<>();
        results.put("total",pageData.getTotalElements());
        results.put("rows",pageData.getContent());
        String json=JSONArray.toJSONString(results);
        ResponseUtils.responseWriter(json);
        return NONE;
    }
}
